package com.xiu.weixin.service.wx;

import java.util.Timer;
import java.util.TimerTask;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.xiu.weixin.pojo.AccessToken;
import com.xiu.weixin.util.Consts;
import com.xiu.weixin.util.net.NetUtil;

import net.sf.json.JSONObject;

//获取access_token
@Service
public class GetAccessTokenService {
	private static final Logger logger = LoggerFactory.getLogger(GetAccessTokenService.class);

	private static AccessToken accessToken;

	private static AccessToken getToken() {
		String url = Consts.GET_ACCESS_TOKEN_URL.replace("APPID", Consts.Test_APPID).replace("APPSECRET",
				Consts.Test_APPSECRET);
		String data = NetUtil.get(url);
		logger.info("获取access_token:" + data);
		JSONObject object = JSONObject.fromObject(data);
		accessToken = new AccessToken(object.getString("access_token"), object.getString("expires_in"));
		// accessToken = (AccessToken) JSONObject.toBean(object, AccessToken.class);
		// 定时主动刷新
		TimerTask timeTask = new TimerTask() {
			@Override
			public void run() {
				logger.info("执行定时任务---获取access_token:" + data);
				getToken();
			}
		};
		new Timer().schedule(timeTask, Integer.parseInt(object.getString("expires_in")) * 1000);
		return accessToken;
	}

	public static String getAccessToken() {
		// 被动刷新
		if (accessToken == null || accessToken.isExpired()) {
			return getToken().getAccess_token();
		} else {
			return accessToken.getAccess_token();
		}

	}

}
